package com.htfyun.factorytest.agingtest;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Message;
import android.os.PowerManager;
import android.view.View;

import androidx.annotation.NonNull;

import com.htfyun.eink.EinkUtils;
import com.htfyun.factorytest.R;
import com.htfyun.factorytest.common.Constants;
import com.htfyun.factorytest.common.FTUtils;
import com.htfyun.factorytest.utils.DebugLog;
import com.htfyun.factorytest.utils.MemTester;
import com.htfyun.factorytest.utils.TimeStringUtils;

import java.io.File;

import top.oply.opuslib.OpusService;

public class TestMemory extends AgingTestItemBase {

    private static final String OPUS = FTUtils.getFTStorageDirectory() + File.separator + "test.opus";
    private static final int MSG_UPDATE_UI = 10;
    private static final int PERIOD_UPDATE_UI = 1000;

    private static final int MSG_RECORD_START = 20;
    private static final int PERIOD_DELAY_START = 3 * 1000;

    private static final int MSG_RECORD_STOP = 21;
    private static final int PERIOD_RECORD_STOP = 5 * 1000;

    private View view;

    public TestMemory(@NonNull Context context, @NonNull View view) {
        super(context, view);
        this.view = view;
    }

    @Override
    protected void handleMessage(Message msg) {
        final int what = msg.what;
        switch (what) {
            case MSG_UPDATE_UI:
                updateMemoryAgingInfo();
                getHandler().sendEmptyMessageDelayed(MSG_UPDATE_UI, PERIOD_UPDATE_UI);
                break;

            case MSG_RECORD_START:
                startRecordTread();
                break;

            case MSG_RECORD_STOP:
                stopRecordThread();
                break;
        }
    }

    @Override
    protected void doStartTest() {
        EinkUtils.forceEinkFullUpdateWithView(view);
        DebugLog.e("TestHardware doStartTest");
        AgingTestItemAttr.setAgingMemoryTestEnabled(getContext(), true);
        startTestRecord();
        startTestMemory();
        acquireWakeLock();
        getHandler().sendEmptyMessage(MSG_UPDATE_UI);
    }

    @Override
    protected void setTestStarted(boolean started) {
        super.setTestStarted(started);
    }

    @Override
    protected void doStopTest() {
        DebugLog.e("TestHardware doStopTest");
        AgingTestItemAttr.setAgingMemoryTestEnabled(getContext(), false);
        getLinearLayoutContainer().setBackgroundColor(Color.TRANSPARENT);

        stopTestRecord();
        stopTestMemory();
        releaseWakeLock();
        getHandler().removeMessages(MSG_UPDATE_UI);
    }

    @Override
    public AgingTestItemAttr getAgingTestItemAttr() {
        return AgingTestItemAttr.memory;
    }

    private void updateMemoryAgingInfo() {

        final long usedTime = AgingTestItemAttr.getAgingTimeTick_ms(getContext()) - getAgingTestItemAttr().getStartTime_ms(getContext());
        final String timeStr = TimeStringUtils.makeTimeString(usedTime);

        String memoryAgingTimeString = getContext().getString(R.string.aging_memory_time_used, timeStr);

        String abnormalShutdownState = getContext().getString(R.string.aging_hardware_abnormal_shutdown, AgingTestItemAttr.getAbnormalShutdownCount(getContext()));

        String allInfo = abnormalShutdownState
                + memoryAgingTimeString;

        updateTxtItemInfo(allInfo);

    }

    ////////////////////////
    // WakeLock
    ////////////////////////

    private PowerManager.WakeLock mWakeLock;

    private void acquireWakeLock() {
        if (mWakeLock == null) {
            PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
            if (pm == null) {
                return;
            }
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                    getClass().getCanonicalName());
            mWakeLock.acquire();

        }
    }

    private void releaseWakeLock() {
        if (mWakeLock != null) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    private boolean isRunning = true;

    private void startTestMemory() {
/*        ActivityManager activityManager = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
        DebugLog.e("getMemoryClass = " + activityManager.getMemoryClass()
                + ",getLargeMemoryClass = " + activityManager.getLargeMemoryClass());*/
        for (int i = 0; i < 8; i++) {
            new Thread(() -> {
                int result;
                while (isRunning) {
                    try {
                        result = MemTester.memtest("16M", 1);
                        if (result != Constants.EXIT_OK) {
                            DebugLog.e("memory test fail, result = " + result);
                            int count = AgingTestItemAttr.getMemoryErrorCount(getContext());
                            AgingTestItemAttr.setMemoryErrorCount(getContext(), ++count);
//                        stopTestMemory();
                        }
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    private void stopTestMemory() {
        isRunning = false;
    }

    //////////////////////
    //    OpusRecorder
    /////////////////////

    /**
     * 要有 record 授权. 对于我们的测试的墨水屏, 他已经授权了
     */
    public void startTestRecord() {
        getHandler().removeMessages(MSG_RECORD_STOP);
        getHandler().sendEmptyMessage(MSG_RECORD_START);
    }

    private void stopTestRecord() {
        stopRecordThread();

        getHandler().removeMessages(MSG_RECORD_STOP);
        getHandler().removeMessages(MSG_RECORD_START);
    }

    private void startRecordTread() {
/*        if (mOpusRecorder == null) {
            mOpusRecorder = OpusRecorder.getInstance();
        }*/
        OpusService.stopRecording(getContext());
        OpusService.record(getContext(), OPUS);
    }

    private void stopRecordThread() {
//        if (mOpusRecorder != null) {
//            mOpusRecorder.stopRecording();
//            mOpusRecorder = null;
//        }
        OpusService.stopRecording(getContext());
    }

    private void startIflytekRecorder() {
        Intent intent = new Intent()
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                .setClassName("com.iflytek.record.ainoterecord", "com.iflytek.record.ainoterecord.ui.activity.RecordingActivity")
                .putExtra("KEY_NOTE_ID", 0L)
                .putExtra("KEY_FOLDER_LOCAL_ID", "FOLDER_LOCAL_ID-1L")
                .putExtra("KEY_IS_STAR", true)
                .putExtra("notebookId", -1L)
                .putExtra("record_stat", "CREATE_OFFLINE");

        try {
            getContext().startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
